package com.calvin.study.multithread.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池的使用
 * 
 * @ClassName:ThreadPoolUseDemo
 * @Description:TODO(描述这个类的作用)
 * @author:Calvin.W
 * @date:2022年2月24日 上午11:47:29
 */
public class ThreadPoolUseDemo {

	public static void main(String[] args) {
		definedThreadPool();
	}

	private static void definedThreadPool() {
		// 线程最大8个
		ExecutorService executor = new ThreadPoolExecutor(2, 5, 1L, TimeUnit.SECONDS,
				new LinkedBlockingDeque<Runnable>(3), Executors.defaultThreadFactory(),
				new ThreadPoolExecutor.CallerRunsPolicy());

		try {
			for (int i = 1, len = 10; i <= len; i++) {
				executor.execute(() -> {
					System.out.println("[窗口" + Thread.currentThread().getName() + "] \t 办理业务");
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			executor.shutdown();
		}

	}

	public static void cachecThread() {
		ExecutorService executor = Executors.newCachedThreadPool();
		try {
			for (int i = 1; i <= 20; i++) {
				executor.execute(() -> {
					System.out.println("[窗口" + Thread.currentThread().getName() + "] \t 办理业务");
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			executor.shutdown();
		}
	}

	public static void singleThread() {
		ExecutorService executor = Executors.newSingleThreadExecutor();
		try {
			for (int i = 1; i <= 10; i++) {
				executor.execute(() -> {
					System.out.println("[窗口" + Thread.currentThread().getName() + "] \t 办理业务");
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			executor.shutdown();
		}
	}

	public static void fixedThreadPool(int nThreads) {
		ExecutorService executor = Executors.newFixedThreadPool(nThreads);// 线程池总量
		try {
			for (int i = 1; i <= 10; i++) {
				executor.execute(() -> {
					System.out.println("[窗口" + Thread.currentThread().getName() + "] \t 办理业务");
				});
			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			executor.shutdown();
		}
	}

}
